package cn.jisol.ngame.client;

import cn.jisol.ngame.client.tool.QueueNClient;
import cn.jisol.ngame.netty.network.udp.session.UDPSession;
import cn.jisol.ngame.proto.message.NGameMessageOuterClass;
import cn.jisol.ngame.rpc.NGameRPC;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.Getter;
import lombok.Setter;

import javax.websocket.Session;
import java.util.Objects;

@Getter
@Setter
public class DefaultNClient extends QueueNClient<NGameMessageOuterClass.NGameMessage, NGameMessageOuterClass.NGameMessage> {

    public Session session;
    public UDPSession udpSession;

    public DefaultNClient(Session session){
        super(session.getId());
        this.session = session;
    }
    
    public DefaultNClient(String uuid, Session session) {
        super(uuid);
        this.session = session;
    }

    public DefaultNClient(UDPSession session){
        super(session.getCId());
        this.udpSession = session;
    }
    public DefaultNClient(String uuid, UDPSession session){
        super(uuid);
        this.udpSession = session;
    }
    
    @Override
    public void onMessage(NGameMessageOuterClass.NGameMessage data) {
        //调用RPC功能
        try {
            NGameRPC.invoke(this,data);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void onSendMessage(NGameMessageOuterClass.NGameMessage message) {
        if(Objects.nonNull(this.getSession()) && this.getSession().isOpen())
            this.getSession().getAsyncRemote().sendObject(message);
        if(Objects.nonNull(this.getUdpSession()) && this.getUdpSession().getIsAlive())
            this.getUdpSession().vSendMessage(message);
    }

    public String getId(){
        if(Objects.nonNull(this.getSession())){
            return this.getSession().getId();
        }else if(Objects.nonNull(this.getUdpSession())){
            return this.getUdpSession().getCId();
        }
        return null;
    }

}
